package com.alexander.cloundexplorer.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alexander.cloundexplorer.R;
import com.alexander.cloundexplorer.adapter.SecondFileTypeAdapter;
import com.alexander.cloundexplorer.bean.params.LoginParams;
import com.alexander.cloundexplorer.bean.params.UploadFileParams;
import com.alexander.cloundexplorer.bean.params.User;
import com.alexander.cloundexplorer.bean.response.BaseResponse;
import com.alexander.cloundexplorer.bean.response.FileAndDirectoryInfoResponse;
import com.alexander.cloundexplorer.bean.response.FileInfoResponse;
import com.alexander.cloundexplorer.bean.response.QuerySecondFileCountResponse;
import com.alexander.cloundexplorer.fragment.BaseFragment;
import com.alexander.cloundexplorer.fragment.SearchClassifyFileFragment;
import com.alexander.cloundexplorer.util.Constants;
import com.alexander.cloundexplorer.util.UriTranslateUtil;
import com.alibaba.fastjson.JSON;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import com.alexander.cloundexplorer.codec.digest.DigestUtils;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @author Administrator
 */
public class MainActivity extends BaseActivity implements SecondFileTypeAdapter.OnItemClickLisnter
{
    @BindView(R.id.recyclerView_Layout)
    RelativeLayout recyclerViewLayout;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.fragment_Layout)
    RelativeLayout fragmentLayout;

    private User user = new User();
    private List<QuerySecondFileCountResponse> list = new ArrayList<>();
    private SecondFileTypeAdapter secondFileTypeAdapter;
    private int selectFileRequestCode = 1;
    private FragmentManager fragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        fragmentManager = getSupportFragmentManager();
        Intent intent = getIntent();
        user = (User) intent.getSerializableExtra("user");

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        secondFileTypeAdapter = new SecondFileTypeAdapter(this, list);
        secondFileTypeAdapter.setOnItemClickLisnter(this);
        recyclerView.setAdapter(secondFileTypeAdapter);

        if (Build.VERSION.SDK_INT >= 23)
        {
            if ((checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
                    || (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED))
            {
                requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1001);
            }
        }
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        OkHttpUtils
                .post()
                .url(Constants.IP.concat("/fileController/querySecondFileCount"))
                .build()
                .execute(new StringCallback()
                {
                    @Override
                    public void onError(Call call, Exception e, int id)
                    {
                        showTip(e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id)
                    {
                        showTip(response);
                        BaseResponse baseResponse = JSON.parseObject(response, BaseResponse.class);
                        list.removeAll(list);
                        list.addAll(JSON.parseArray(baseResponse.getData().toString(), QuerySecondFileCountResponse.class));
                        secondFileTypeAdapter.notifyDataSetChanged();
                    }
                });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.menu_options_classifyfile, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.search:
                fragmentManager.popBackStack();
                BaseFragment baseFragment = SearchClassifyFileFragment.getInstance(new LoginParams(user.getPhone(), user.getPassword()));
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.fragment_Layout, baseFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                return true;
            case R.id.root:
                Intent intent = new Intent(MainActivity.this, FileListActivity.class);
                intent.putExtra("user", user);
                FileAndDirectoryInfoResponse fileAndDirectoryInfoResponse = new FileAndDirectoryInfoResponse();
                /**这里的ID应该是用户的根目录的ID   服务端没写好   注册的时候update一下*/
                fileAndDirectoryInfoResponse.setId(user.getRootdir_id());
                intent.putExtra("fileInfo", fileAndDirectoryInfoResponse);
                MainActivity.this.startActivity(intent);
                return true;
            case R.id.trash:
                Intent intent1 = new Intent(MainActivity.this, TrashActivity.class);
                intent1.putExtra("user", user);
                MainActivity.this.startActivity(intent1);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @OnClick(R.id.textView)
    public void onViewClicked()
    {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        /**文件类型无限制*/
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, selectFileRequestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        String filePath = null;
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == selectFileRequestCode && resultCode == Activity.RESULT_OK)
        {
            Uri uri = data.getData();
            if ("file".equalsIgnoreCase(uri.getScheme()))
            {
                filePath = uri.getPath();
            }
            UriTranslateUtil uriTranslateUtil = UriTranslateUtil.getInstance();
            /**4.4以后的获取路径方法*/
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT)
            {
                filePath = uriTranslateUtil.getPath(this, uri);
            } else
            {
                /**4.4以下下系统调用方法*/
                filePath = uriTranslateUtil.getRealPathFromURI(uri, MainActivity.this);
            }
        }
        upload(filePath);
    }

    private void upload(String filePath)
    {
        try
        {
            File file = new File(filePath);
            UploadFileParams uploadFileParams = new UploadFileParams();
            uploadFileParams.setFileCount("1");
            uploadFileParams.setAccount(user.getPhone());
            uploadFileParams.setPassword(user.getPassword());
            FileInputStream fileInputStream = new FileInputStream(file);
            String md5 = DigestUtils.md5Hex(fileInputStream);
            uploadFileParams.setFileMD5(md5);
            uploadFileParams.setFatherDirectoryId(user.getRootdir_id());
            String json = JSON.toJSONString(uploadFileParams);
            OkHttpUtils.post()
                    .url(Constants.IP.concat("/fileController/uploadFile"))
                    .addParams("params", json)
                    .addFile("file", file.getName(), file)
                    .build()
                    .connTimeOut(100000)
                    .readTimeOut(100000)
                    .writeTimeOut(100000)
                    .execute(new StringCallback()
                    {
                        @Override
                        public void onError(Call call, Exception e, int id)
                        {
                            System.out.println("出错出错出错");
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(String response, int id)
                        {
                            System.out.println("上传成功");
                            System.out.println(response);
                        }
                    });
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(int position)
    {
        showTip(String.valueOf(position));
        Intent intent = new Intent(MainActivity.this, ClassifyFilesActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("user", user);
        intent.putExtras(bundle);
        intent.putExtra("id", list.get(position).getId().toString());
        MainActivity.this.startActivity(intent);
    }
}
